//
//  CMCFBShareViewController.m
//  MobHuntApp
//
//  Created by Nong Trung Nghia on 9/19/12.
//  Copyright (c) 2012 CMC Software. All rights reserved.
//

#import "CMCFBShareViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "AppDelegate.h"
#import <FacebookSDK/FacebookSDK.h>

#import "LoadingView.h"
@interface CMCFBShareViewController ()

@end

@implementation CMCFBShareViewController
@synthesize image=_image;
@synthesize text=_text;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

+(void)presentViewController:(UIViewController*)vc{
    [[[[UIApplication sharedApplication] delegate] window] addSubview:vc.view];
}

+(void)dismissFBViewController{
    for (UIView *view in [[[[UIApplication sharedApplication] delegate] window] subviews]) {
        if (view.tag==9999) {
            [view removeFromSuperview];
            return;
        }
    }
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [[[UIApplication sharedApplication] delegate] window];
    
    UIView *_frameView=[[UIView alloc] initWithFrame:CGRectMake(0, 10, 320, 217)];
    [_frameView setBackgroundColor:[UIColor clearColor]];
    UIImageView *_backgroundImageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"FBShareBG.png"]];
    [_backgroundImageView setFrame:CGRectMake(0, 0, 320, 217)];
    [_frameView addSubview:_backgroundImageView];
    [_frameView sendSubviewToBack:_backgroundImageView];
    [_backgroundImageView release];
    _textView=[[UITextView alloc] initWithFrame:CGRectMake(5, 60, 210, 115)];
    [_textView setAutocorrectionType:UITextAutocorrectionTypeNo];
    [_textView setBackgroundColor:[UIColor clearColor]];
    [_textView becomeFirstResponder];
    if (_image) {
        UIView *backgroundImage=[[UIView alloc] initWithFrame:CGRectMake(220, 60, 90, 110)];
        UIImageView *imageView=[[UIImageView alloc] initWithImage:_image];
        _image=imageView.image;
        [imageView setFrame:CGRectMake(1, 1, 88, 108)];
        [imageView setContentMode:UIViewContentModeScaleAspectFit];
        [backgroundImage addSubview:imageView];
        [imageView release];
        [_frameView addSubview:backgroundImage];
        [backgroundImage release];
    }
    else{
        [_textView setFrame:CGRectMake(5, 60, 300, 115)];
    }
    if (_text) {
        [_textView setText:_text];
    }
    [_frameView addSubview:_textView];
    
    UIButton *sendBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [sendBtn setFrame:CGRectMake(258, 16, 51, 30)];
    [sendBtn addTarget:self action:@selector(post) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *cancelBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setFrame:CGRectMake(10, 16, 57, 30)];
    [cancelBtn addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];

    [_frameView addSubview:sendBtn];
    [_frameView addSubview:cancelBtn];
    [self.view addSubview:_frameView];
    [_frameView release];
    self.view.backgroundColor=[UIColor clearColor];
    self.view.tag=9999;
	// Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)checkLogin{
    if (FBSession.activeSession.isOpen) {
        [self sendRequests];
    } else {
        
        [FBSession openActiveSessionWithPermissions:[NSArray arrayWithObjects:@"publish_stream", nil]
                                       
                                       allowLoginUI:YES
                                  completionHandler:^(FBSession *session,
                                                      FBSessionState status,
                                                      NSError *error) {
                                      // if login fails for any reason, we alert
                                      if (error) {
                                          UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                                          message:error.localizedDescription
                                                                                         delegate:nil
                                                                                cancelButtonTitle:@"OK"
                                                                                otherButtonTitles:nil];
                                          [alert show];
                                          [alert release];
                                          [self.view removeFromSuperview];
                                      } else if (FB_ISSESSIONOPENWITHSTATE(status)) {
                                          [self sendRequests];
                                      }
                                  }];
    }
}

-(void)sendRequests {
            
    FBRequestConnection *newConnection = [[[FBRequestConnection alloc] init] autorelease];
    
    NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
    [params setValue:_textView.text forKey:@"message"];
    if (_image) {
        [params setValue:[_image retain] forKey:@"source"];
    }
    
    [newConnection addRequest:[FBRequest requestWithGraphPath:@"me/photos" parameters:params HTTPMethod:@"POST"]
    completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
        
        if (error) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                            message:error.localizedDescription
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
            
        }
        DBLOG(@"RESULT:%@",result);
//        [self.view removeFromSuperview];
//        [CMCFBShareViewController dismissFBViewController];
        [self.view removeFromSuperview];

    }];
    [newConnection start];

}


-(void)cancel{
    [_textView resignFirstResponder];
    [self.view removeFromSuperview];
}

-(void)post{
    _text=_textView.text;
    if ([_text isEqualToString:@""]||_text==nil) {
        return;
    }
    [self checkLogin];
    [self.view setUserInteractionEnabled:NO];
}


@end
